//
//  MyViewController.swift
//  ReadHub
//
//  Created by 龙轶群 on 2017/8/14.
//  Copyright © 2017年 longyiqun. All rights reserved.
//

import Foundation
import SwiftMoment
import PKHUD
import Eureka
import ViewRow
import Alamofire
import SwiftyJSON
import AlamofireImage
import ParallaxHeader


class MyViewController: FormViewController {
    
    // 定义全局变量
	
	// ICON 64*64
	// ICON Color #8a8a8a
	// 千牛图标库
	
	// nickname
    var name: String? = ""
	
	// mobile
	var mobile: String? = ""
	
	// password
	var pwd: String? = ""
	
	// userid
	var userid: String? = ""
    

    // 开始
	override func viewDidLoad() {
		super.viewDidLoad()
        
        edgesForExtendedLayout = .top
		
		// 背景颜色
		tableView.backgroundColor = Constants.mainBackGroundColor
        
        let imageView = UIImageView()
        imageView.image = UIImage(named: "1jpg")
        imageView.contentMode = .scaleAspectFill
        
        tableView.parallaxHeader.view = imageView
        tableView.parallaxHeader.height = 250
        tableView.parallaxHeader.minimumHeight = 0
        tableView.parallaxHeader.mode = .topFill
		tableView.showsVerticalScrollIndicator = false
		tableView.showsHorizontalScrollIndicator = false
		tableView.separatorColor = UIColor.clear
        
		
		// 检查是否已经登录
		let userName = UserDefaults.standard.string(forKey: "username")

		if( userName != nil && userName != "") {
			// 已登录, 跳转到自己的面板
			viewUser()
		} else {
			// 去登录 或者注册
			goNew()
		}
	}
	
	// 监测TextField - mobile方法, 并复制到全局变量
	@objc func textFieldDidChangeMobile(sender: UITextField) {
		self.mobile = sender.text!
	}
	
	// 监测TextField - password方法
	@objc func textFieldDidChangePassword(sender: UITextField) {
		self.pwd = sender.text!
	}
	
	// 监测TextField - nickname方法
	@objc func textFieldDidChangeNickname(sender: UITextField) {
		self.name = sender.text!
	}
	
	
	// 注册流程
	
	func registerUser() {
		
		form.removeAll()
		
		// FORM开始
		form +++
			
			// 高度为0的header
            Section() { section in
                var header = HeaderFooterView(title: "")
                header?.onSetupView = { view,  _ in
                }
                header?.height = { 0.000001 }
                section.header = header
            }
            
            <<< ViewRow<RegisterView>("view") { (row) in
				}
				.cellSetup { (cell, row) in
					
					let bundle = Bundle.main
					let nib = UINib(nibName: "RegisterView", bundle: bundle)
					
					cell.view = nib.instantiate(withOwner: self, options: nil)[0] as? RegisterView
					
					cell.contentView.addSubview(cell.view!)
					
					cell.height = { return CGFloat(181) }
					
					cell.viewLeftMargin = 0.0
					cell.viewRightMargin = 0.0
					
					cell.view?.mobileText.addTarget(self, action: #selector(MyViewController.textFieldDidChangeMobile(sender:)), for: UIControlEvents.editingChanged)
					cell.view?.passwordText.addTarget(self, action: #selector(MyViewController.textFieldDidChangePassword(sender:)), for: UIControlEvents.editingChanged)
					cell.view?.nicknameText.addTarget(self, action: #selector(MyViewController.textFieldDidChangeNickname(sender:)), for: UIControlEvents.editingChanged)
					
			}
			+++ Section()
			<<< ViewRow<TwoButtonView2>("TwoButtonView2") { (row) in
				}
				.cellSetup { (cell, row) in
					
					let bundle = Bundle.main
					let nib = UINib(nibName: "TwoButtonView2", bundle: bundle)
					
					cell.view = nib.instantiate(withOwner: self, options: nil)[0] as? TwoButtonView2
					
					cell.contentView.addSubview(cell.view!)
					
					cell.backgroundColor = UIColor.clear
					
					cell.height = { return CGFloat(80) }
					
					cell.viewLeftMargin = 0.0
					cell.viewRightMargin = 0.0
					
					cell.view?.loginBtn.addTarget(self, action: #selector(self.tappedToLoginBtn), for: .touchUpInside)
					cell.view?.doneBtn.addTarget(self, action: #selector(self.tappedDoneBtn), for: .touchUpInside)
			}
	}
	
	// 展示用户详情
	func viewUser() {
		goEdit()
	}

	
	internal func goEdit() -> () {
		
		let userName = UserDefaults.standard.string(forKey: "username")
		let mobile = UserDefaults.standard.string(forKey: "mobile")
		
		self.form.removeAll()
		
		form +++
			
			// 高度为0的header
			Section() { section in
				var header = HeaderFooterView(title: "")
				header?.onSetupView = { view,  _ in
				}
				header?.height = { 0.000001 }
				section.header = header
			}
			
			<<< LabelRow(){ row in
				row.title = "昵称"
				row.value = userName
				row.cell.textLabel?.font = UIFont.systemFont(ofSize: 20.0)
				row.cell.detailTextLabel?.font = UIFont.systemFont(ofSize: 20.0)
				}.cellSetup {cell, row in
					cell.imageView?.image = UIImage(named: "my_nickname")
			}
			
			
			<<< LabelRow(){ row in
				row.title = "手机号"
				row.value = mobile
				
				}.cellSetup {cell, row in
					cell.imageView?.image = UIImage(named: "my_mobile")
//					row.cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 15.0)
//					row.cell.textLabel?.textColor = UIColor.red
//					row.cell.textLabel?.tintColor = UIColor.red
			}
			
			<<< LabelRow(){ row in
				row.title = "站内信"
				row.value = "0"
				}.cellSetup {cell, row in
					cell.imageView?.image = UIImage(named: "my_mail")
			}
		
			
			<<< ButtonRow("Setting") {
				$0.title = "设置"
				$0.presentationMode = .show(controllerProvider: .callback(builder: {
					
					//拿到storyBoard
					let storyBoard = UIStoryboard(name: "Main", bundle: nil)
					//拿到ViewController
					let destination = storyBoard.instantiateViewController(withIdentifier: "SettingViewController") as! SettingViewController
					
					return destination
				}), onDismiss:nil)
				}.cellSetup {cell, row in
					cell.imageView?.image = UIImage(named: "my_setting")
			}
			
			<<< ButtonRow("About") {
				$0.title = "关于"
				$0.presentationMode = .show(controllerProvider: .callback(builder: {
					
					//拿到storyBoard
					let storyBoard = UIStoryboard(name: "Main", bundle: nil)
					//拿到ViewController
					let destination = storyBoard.instantiateViewController(withIdentifier: "AboutViewController") as! AboutViewController
					
					return destination
				}), onDismiss:nil)
				}.cellSetup {cell, row in
					cell.imageView?.image = UIImage(named: "my_about")
			}
			
			+++ Section()
			<<< ViewRow<OneButtonView>("OneButtonView") { (row) in
				}
				.cellSetup { (cell, row) in
					
					let bundle = Bundle.main
					let nib = UINib(nibName: "OneButtonView", bundle: bundle)
					
					cell.view = nib.instantiate(withOwner: self, options: nil)[0] as? OneButtonView
					
					cell.contentView.addSubview(cell.view!)
					
					cell.backgroundColor = UIColor.clear
					
					cell.height = { return CGFloat(80) }
					
					cell.viewLeftMargin = 0.0
					cell.viewRightMargin = 0.0
					
					cell.view?.logoutBtn.addTarget(self, action: #selector(self.tappedToLogoutBtn), for: .touchUpInside)
					
			}
	}
	
	// 登录流程
	internal func goNew() -> () {
		
		form.removeAll()
		
		// FORM开始
		form +++
			
			// 高度为0的header
			Section() { section in
				var header = HeaderFooterView(title: "")
				header?.onSetupView = { view,  _ in
				}
				header?.height = { 0.000001 }
				section.header = header
			}
            
			<<< ViewRow<LoginView>("view") { (row) in
				}
				.cellSetup { (cell, row) in
					
					let bundle = Bundle.main
					let nib = UINib(nibName: "LoginView", bundle: bundle)
					
					cell.view = nib.instantiate(withOwner: self, options: nil)[0] as? LoginView
					
					cell.contentView.addSubview(cell.view!)
					
					cell.height = { return CGFloat(121) }
					
					cell.viewLeftMargin = 0.0
					cell.viewRightMargin = 0.0
					
					
					cell.view?.mobileText.addTarget(self, action: #selector(MyViewController.textFieldDidChangeMobile(sender:)), for: UIControlEvents.editingChanged)
					cell.view?.passwordText.addTarget(self, action: #selector(MyViewController.textFieldDidChangePassword(sender:)), for: UIControlEvents.editingChanged)
			}

			+++ Section()
			<<< ViewRow<TwoButtonView>("TwoButtonView") { (row) in
				}
				.cellSetup { (cell, row) in
					
					let bundle = Bundle.main
					let nib = UINib(nibName: "TwoButtonView", bundle: bundle)
					
					cell.view = nib.instantiate(withOwner: self, options: nil)[0] as? TwoButtonView
					
					cell.contentView.addSubview(cell.view!)
					
					cell.backgroundColor = UIColor.clear
					
					cell.height = { return CGFloat(80) }
					
					cell.viewLeftMargin = 0.0
					cell.viewRightMargin = 0.0
					
					cell.view?.loginBtn.addTarget(self, action: #selector(self.tappedLoginBtn), for: .touchUpInside)
					cell.view?.regBtn.addTarget(self, action: #selector(self.tappedRegBtn), for: .touchUpInside)
			}
		
	}
	
	@objc func tappedLoginBtn() -> () {
		let loginURL: URLConvertible = Constants.loginURL
		
		let para = ["mobile": self.mobile!, "password": self.pwd!];
		
		HUD.show(HUDContentType.labeledProgress(title: "Loading...", subtitle: ""))
		
		// CALL API
		Alamofire.request(loginURL, method: .get, parameters: para).responseJSON { response in
			
			if let JSONEntity = response.result.value {
				
				let jsonData = JSON(JSONEntity)
				
				// 判断是否登录成功
				if (jsonData["data"]["code"] == 0){
					
					// 更新全局变量
					self.name = jsonData["data"]["info"]["nickname"].stringValue
					self.mobile = jsonData["data"]["info"]["mobile"].stringValue
					self.userid = jsonData["data"]["info"]["id"].stringValue
					
					// 更新用户信息(本地)
					UserDefaults.standard.set(self.name, forKey: "username")
					UserDefaults.standard.set(self.mobile, forKey: "mobile")
					UserDefaults.standard.set(self.userid, forKey: "userid")
					
					HUD.hide()
					
					// 跳转到My页面
					self.viewUser()
					
				} else {
					HUD.flash(HUDContentType.label("Error"), delay: 1)
				}
			}
		} // CALL DONE
	}
	
	// 点击注册按钮
	@objc func tappedRegBtn() -> () {
		self.registerUser()
	}
	
	// 点击登录按钮
	@objc func tappedToLoginBtn() -> () {
		self.goNew()
	}
	
	// 点击注销按钮
	@objc func tappedToLogoutBtn() -> () {
		
		self.form.removeAll()
		
		// 注销本地数据
		UserDefaults.standard.set("", forKey: "username")
		UserDefaults.standard.set("", forKey: "mobile")
		UserDefaults.standard.set("", forKey: "pwd")
		UserDefaults.standard.set("", forKey: "userid")
		
		// 更新全局变量
		self.name = ""
		self.mobile = ""
		self.pwd = ""
		self.userid = ""
		
		self.goNew()
	}
	
	// 点击完成按钮
	@objc func tappedDoneBtn() -> () {
		// 准备URL
		let registerURL: URLConvertible = Constants.registerURL
		let para = ["mobile": self.mobile!, "password": self.pwd!, "nickname": self.name!]
		
		HUD.show(HUDContentType.labeledProgress(title: "Loading...", subtitle: ""))
		
		// CALL API
		Alamofire.request(registerURL, method: .get, parameters: para).responseJSON { response in
			
			if let JSONEntity = response.result.value {
				
				let jsonData = JSON(JSONEntity)
				
				// 判断是否登录成功
				if (jsonData["data"]["code"] == 0){
					
					// 更新全局变量
					self.name = jsonData["data"]["info"]["nickname"].stringValue
					self.mobile = jsonData["data"]["info"]["mobile"].stringValue
					self.userid = jsonData["data"]["info"]["id"].stringValue
					
					// 更新用户信息(本地)
					UserDefaults.standard.set(self.name, forKey: "username")
					UserDefaults.standard.set(self.mobile, forKey: "mobile")
					UserDefaults.standard.set(self.userid, forKey: "userid")
					
					HUD.hide()
					
					// 跳转到My页面
					self.viewUser()
					
				} else {
					HUD.flash(HUDContentType.label("Error"), delay: 1)
				}
			}
		} // CALL DONE
	}
	
}
